package com.hanthink.web.controller.pc;

import java.util.List;

import com.hanthink.common.exception.CustomException;
import org.apache.commons.lang.StringUtils;
import org.apache.velocity.runtime.directive.Foreach;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.hanthink.common.annotation.Log;
import com.hanthink.common.constant.BusinessConstants;
import com.hanthink.common.core.controller.BaseController;
import com.hanthink.common.core.domain.AjaxResult;
import com.hanthink.common.core.domain.entity.SysDept;
import com.hanthink.common.core.domain.model.LoginUser;
import com.hanthink.common.core.page.TableDataInfo;
import com.hanthink.common.enums.BusinessType;
import com.hanthink.common.utils.SerialNumberUtil;
import com.hanthink.common.utils.ServletUtils;
import com.hanthink.common.utils.poi.ExcelUtil;
import com.hanthink.framework.web.service.TokenService;
import com.hanthink.quartz.domain.TaskSelectInfo;
import com.hanthink.quartz.mapper.TaskMapper;
import com.hanthink.system.domain.SysSerialNumber;
import com.hanthink.system.domain.pc.EmItemFile;
import com.hanthink.system.domain.pc.EmJobItem;
import com.hanthink.system.domain.pc.EmTask;
import com.hanthink.system.domain.pc.EmTaskItem;
import com.hanthink.system.mapper.SysDeptMapper;
import com.hanthink.system.mapper.SysSerialNumberMapper;
import com.hanthink.system.service.pc.IEmItemFileService;
import com.hanthink.system.service.pc.IEmJobItemService;
import com.hanthink.system.service.pc.IEmTaskItemService;
import com.hanthink.system.service.pc.IEmTaskService;

/**
 * 任务管理Controller
 * 
 * @author hanthink
 * @date 2021-01-22
 */
@RestController
@RequestMapping("/equipment/task")
public class EmTaskController extends BaseController {
	@Autowired
	private IEmTaskService emTaskService;

	@Autowired
	private IEmJobItemService emJobItemService;

	@Autowired
	private SysSerialNumberMapper sysSerialNumberMapper;

	@Autowired
	private IEmTaskItemService emTaskItemService;

	@Autowired
	private IEmItemFileService emItemFileService;

	@Autowired
	private TaskMapper taskMapper;

	@Autowired
	private TokenService tokenService;

	@Autowired
	private SysDeptMapper sysDeptMapper;

	/**
	 * 查询任务管理列表
	 */
	@PreAuthorize("@ss.hasPermi('equipment:task:list')")
	@GetMapping("/list")
	public TableDataInfo list(EmTask emTask) {
		startPage();
		LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
		if (loginUser.getUser().getDept().getParentId() != 0L && loginUser.getUser().getSite() != null) {
			emTask.setSiteKey(loginUser.getUser().getSite().toString());
		}
		if (loginUser.getUser().getDept().getParentId() != 0L && loginUser.getUser().getHangame() != null) {
			emTask.setHangameKey(loginUser.getUser().getHangame().toString());
		}
		List<EmTask> list = emTaskService.selectEmTaskList(emTask);
		return getDataTable(list);
	}

	/**
	 * 导出任务管理列表
	 */
	@PreAuthorize("@ss.hasPermi('equipment:task:export')")
	@Log(title = "任务管理", businessType = BusinessType.EXPORT)
	@GetMapping("/export")
	public AjaxResult export(EmTask emTask) {
		LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
		if (loginUser.getUser().getDept().getParentId() != 0L && loginUser.getUser().getSite() != null) {
			emTask.setSiteKey(loginUser.getUser().getSite().toString());
		}
		if (loginUser.getUser().getDept().getParentId() != 0L && loginUser.getUser().getHangame() != null) {
			emTask.setHangameKey(loginUser.getUser().getHangame().toString());
		}
		List<EmTask> list = emTaskService.selectEmTaskList(emTask);
		ExcelUtil<EmTask> util = new ExcelUtil<EmTask>(EmTask.class);
		return util.exportExcel(list, "task");
	}

	/**
	 * 获取任务管理详细信息
	 */
	@PreAuthorize("@ss.hasPermi('equipment:task:query')")
	@GetMapping(value = "/{taskCode}")
	public AjaxResult getInfo(@PathVariable("taskCode") String taskCode) {
		return AjaxResult.success(emTaskService.selectEmTaskById(taskCode));
	}

	/**
	 * 新增任务管理
	 */
	@PreAuthorize("@ss.hasPermi('equipment:task:add')")
	@Log(title = "任务管理", businessType = BusinessType.INSERT)
	@PostMapping
	public AjaxResult add(@RequestBody EmTask emTask) {
		return toAjax(emTaskService.insertEmTask(emTask));
	}

	/**
	 * 修改任务管理
	 */
	@PreAuthorize("@ss.hasPermi('equipment:task:edit')")
	@Log(title = "任务管理", businessType = BusinessType.UPDATE)
	@PutMapping
	public AjaxResult edit(@RequestBody EmTask emTask) {
		LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
		String username = loginUser.getUsername();
		return toAjax(emTaskService.updateEmTask(emTask,username));
	}

	/**
	 * 删除任务管理
	 */
	@PreAuthorize("@ss.hasPermi('equipment:task:remove')")
	@Log(title = "任务管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{taskCodes}")
	public AjaxResult remove(@PathVariable String[] taskCodes) {
		LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
		String username = loginUser.getUsername();
		return toAjax(emTaskService.deleteEmTaskByIds(taskCodes,username));
	}

	/**
	 * 验证工艺点检任务
	 */
	@PostMapping("/checkCraft")
	public AjaxResult checkCraft(@RequestBody EmTask emTask) {

		return AjaxResult.success(emTaskService.selectNoFinishEmTaskList(emTask));
	}


	/**
	 * 创建新的工艺点检单
	 */
	@Log(title = "创建工艺点检单", businessType = BusinessType.INSERT)
	@PostMapping("/creatCraft")
	@Transactional(rollbackFor = Exception.class)
	public AjaxResult creatCraft(@RequestBody EmTask emTask) {
		if (ObjectUtils.isEmpty(emTask) || StringUtils.isBlank(emTask.getEqKey())) {
			return AjaxResult.error("设备条码不能为空！");
		}
		try {
			if (StringUtils.isEmpty(emTask.getEquipCode())) {
				throw new CustomException("设备码EquipCode不能为空");
			}

			// 查询设备对应工艺点检项
			EmJobItem emJobItem = new EmJobItem();
			emJobItem.setEqKey(emTask.getEquipCode());
			emJobItem.setItemType("3");
			emJobItem.setStatus("1");
			List<EmJobItem> list = emJobItemService.selectEmJobItemList(emJobItem);

			if (list.size() == 0) {
				return AjaxResult.error("没有找到设备对应的点检项目，请核实！");
			}

			// 获取序列号
			SysSerialNumber serial = sysSerialNumberMapper.selectNextValue();
			String taskCode = SerialNumberUtil.getSerialNumber(BusinessConstants.CHECK_FLAG, serial.getNextValue(),
					serial.getToday());
			emTask.setTaskCode(taskCode);// 任务编码
			// 关联事业部
			LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
			if (loginUser.getUser().getDept().getParentId() != 0L && loginUser.getUser().getSite() != null) {
				SysDept sysDept = sysDeptMapper.selectDeptById(loginUser.getUser().getSite());
				emTask.setHangameKey(sysDept.getParentId().toString());
			}
			emTask.setTaskType("3"); // 工艺点检
			emTask.setStatus("0");// 未执行
			emTask.setEqStatus("1");
			emTask.setProgress("0/" + list.size()); // 进度
			// 创建任务项
			emTaskService.insertEmTask(emTask);

			List<EmTask> taskList = emTaskService.selectEmTaskList(emTask);
			if (taskList.size() > 0) {
				// 创建点检项
				if (list.size() > 0) {
					EmTaskItem item = null;
					for (EmJobItem jobItem : list) {
						item = new EmTaskItem();
						item.setTaskKey(taskCode);
						item.setItemCode(jobItem.getItemCode());
						item.setItemName(jobItem.getItemName());
						item.setItemDesc(jobItem.getItemDesc());
						item.setItemType(jobItem.getCategory());
						item.setExecuteMeans(jobItem.getExecuteMeans());
						item.setFilePath(jobItem.getFilePath());
						item.setOrderNum(jobItem.getSortNum());
						item.setSiteKey(Long.valueOf(emTask.getSiteKey()));
						// 保存点检子项
						emTaskItemService.insertEmTaskItem(item);
						List<EmTaskItem> newItems = emTaskItemService.selectEmTaskItemList(item);
						if (!StringUtils.isBlank(jobItem.getExecuteMeans()) && "4".equals(jobItem.getExecuteMeans())) {
							// 查询子项并保存
							EmItemFile emItemFile = new EmItemFile();
							emItemFile.setItemId(jobItem.getId());
							List<EmItemFile> itemFileList = emItemFileService.selectEmItemFileList(emItemFile);
							if (itemFileList.size() > 0 && newItems.size() > 0) {
								TaskSelectInfo taskSelectInfo = null;
								for (EmItemFile emItem : itemFileList) {
									taskSelectInfo = new TaskSelectInfo();
									taskSelectInfo.setItemId(newItems.get(0).getId());
									taskSelectInfo.setSelectCode(emItem.getSelectCode());
									taskSelectInfo.setSelectDesc(emItem.getSelectDesc());
									taskSelectInfo.setFilePath(emItem.getFilePath());
									taskMapper.insertTaskSelect(taskSelectInfo);
								}
							}

						}
					}

				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e.toString());
		}

		return AjaxResult.success(emTask);
	}


	@Log(title = "创建工艺点检单", businessType = BusinessType.INSERT)
	@PostMapping("/creatCraftPlus")
	@Transactional(rollbackFor = Exception.class)
	public AjaxResult creatCraftPlus(@RequestBody EmTask emTask) {
		if (ObjectUtils.isEmpty(emTask) || StringUtils.isBlank(emTask.getEqKey())) {
			return AjaxResult.error("设备条码不能为空！");
		}
		try {
			if (StringUtils.isEmpty(emTask.getEquipCode())) {
				throw new CustomException("设备码EquipCode不能为空");
			}

			// 查询设备对应工艺点检项
			EmJobItem emJobItem = new EmJobItem();
			emJobItem.setEqKey(emTask.getEquipCode());
			emJobItem.setItemType("3");
			emJobItem.setStatus("1");
			List<EmJobItem> list = emJobItemService.selectEmJobItemList(emJobItem);

			if (list.size() == 0) {
				return AjaxResult.error("没有找到设备对应的点检项目，请核实！");
			}

			//根据设备ID查询taskno
			String taskCode = emTaskService.selectEmTaskListPlus(emTask.getEquipCode());
			emTask.setTaskCode(taskCode);// 任务编码
			// 关联事业部
			LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
			if (loginUser.getUser().getDept().getParentId() != 0L && loginUser.getUser().getSite() != null) {
				SysDept sysDept = sysDeptMapper.selectDeptById(loginUser.getUser().getSite());
				emTask.setHangameKey(sysDept.getParentId().toString());
			}
			emTask.setTaskType("3"); // 工艺点检
			emTask.setStatus("0");// 未执行
			emTask.setEqStatus("1");
			emTask.setProgress("0/" + list.size()); // 进度

		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e.toString());
		}

		return AjaxResult.success(emTask);
	}

	@Test
	public void creatCraftPlus() {
		try {

			//String taskCode = emTaskService.selectEmTaskListPlus("MT01");


		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e.toString());
		}

	}
}
